package com.xinqi.modules.databank.v2.service.part.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinqi.common.base.dto.QuestionBaseDTO;
import com.xinqi.common.base.response.R;
import com.xinqi.common.core.enums.ClassRoleEnum;
import com.xinqi.common.core.enums.ResourcePartTypeEnum;
import com.xinqi.common.satoken.utils.LoginHelper;
import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.modules.course.clazz.client.ClassStudentClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassStudentResultDTO;
import com.xinqi.modules.databank.v1.domain.CourseInteractionSubmitEntity;
import com.xinqi.modules.databank.v1.domain.CourseQuestionLibraryEntity;
import com.xinqi.modules.databank.dto.req.CourseResourcePartQueryDTO;
import com.xinqi.modules.databank.dto.req.CourseResourceVideoQueryDTO;
import com.xinqi.modules.databank.dto.rsp.question.QuestionResultDTO;
import com.xinqi.modules.databank.dto.rsp.question.UserQuestionResultDTO;
import com.xinqi.modules.databank.v1.manager.CourseInteractionSubmitManager;
import com.xinqi.modules.databank.v1.manager.CourseQuestionLibraryManager;
import com.xinqi.modules.databank.v2.convert.CommonQuestionConvert;
import com.xinqi.modules.databank.v2.convert.CourseQuestionLibraryConvert;
import com.xinqi.modules.databank.v2.convert.CourseResourceAnswerConvert;
import com.xinqi.modules.databank.v2.domain.CourseResourceEntity;
import com.xinqi.modules.databank.v2.domain.CourseResourceInteractionLogEntity;
import com.xinqi.modules.databank.v2.domain.CourseResourcePartEntity;
import com.xinqi.modules.databank.v2.manager.*;
import com.xinqi.modules.databank.v2.service.part.ResourcePartService;
import com.xinqi.modules.databank.v2.util.QuestionUtil;
import groovy.lang.Lazy;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 资料库-资料-试题-方法
 * @author dzy
 */
@Service
@RequiredArgsConstructor
public class ResourcePartServiceImpl implements ResourcePartService {

    private final CourseResourcePartManager resourcePartManager;

    private final CourseResourceBaseManager courseResourceBaseManager;

    private final ResourceInteractionLogManager resourceInteractionLogManager;

    private final CourseQuestionLibraryConvert courseQuestionLibraryConvert;
    private final CourseQuestionLibraryManager courseQuestionLibraryManager;

    private final CourseResourceAnswerConvert resourceAnswerConvert;
    private final CourseInteractionSubmitManager interactionSubmitManager;

    @Lazy
    private final ClassStudentClient classStudentClient;

    private final CommonQuestionConvert questionConvert;

    /**
     * 获取 资料 试题
     * @param query 资料ID
     */
    @Override
    public List<CourseResourcePartEntity> selectPart(CourseResourcePartQueryDTO query) {

        // 判断是否数据存在
        CourseResourceEntity entity = Optional.ofNullable(courseResourceBaseManager.getById(query.getContentId()))
            .orElseThrow(() -> CommonErrors.NOT_DATA.asException("course.resource.data.id.not.exit"));

        LambdaQueryWrapper<CourseResourcePartEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseResourcePartEntity::getContentId, entity.getId());
        List<CourseResourcePartEntity> list = resourcePartManager.list(wrapper);
        // 旧数据兼容
        list.forEach(part -> {
            if (Objects.equals(ResourcePartTypeEnum.QUESTION.getCode(), part.getInteractionType())) {
                if (Objects.isNull(part.getQuestions())) {
                    List<CourseQuestionLibraryEntity> librarys = courseQuestionLibraryManager.findByPartId(part.getId());
                    List<QuestionBaseDTO> questionBaseList = courseQuestionLibraryConvert.convertBase(librarys);
                    part.setQuestions(QuestionUtil.tranOptionList(questionBaseList));
                }
            }
        });

        // 获取访问用户信息
        Long userId = LoginHelper.getUserId();
        ClassStudentResultDTO student = R.as(classStudentClient.findByStudentId(entity.getClassId(), userId));

        // 学生则隐藏 答案和解析
        if (Objects.equals(ClassRoleEnum.REPRESENTATIVE.getCode(), student.getClassRole())
            || Objects.equals(ClassRoleEnum.STUDENT.getCode(), student.getClassRole())) {
            list.forEach(part -> {
                if (Objects.equals(ResourcePartTypeEnum.QUESTION.getCode(), part.getInteractionType())) {
                    if (CollectionUtils.isNotEmpty(part.getQuestions())) {
                        part.getQuestions().forEach(item -> {QuestionUtil.initNoAnswerBaseQuestion(item);});
                    }
                }
            });
        }
        return list;
    }

    /**
     * 获取 资料库 试题 通过文件ID
     * @param query 资料ID
     */
    @Override
    public UserQuestionResultDTO selectPartByResourceId(CourseResourcePartQueryDTO query) {
        // 判断是否数据存在
        CourseResourceEntity entity = Optional.ofNullable(courseResourceBaseManager.getById(query.getContentId()))
            .orElseThrow(() -> CommonErrors.NOT_DATA.asException("course.resource.data.id.not.exit"));

        CommonErrors.BAD_REQUEST.check(Objects.nonNull(query.getResourceId()), "文件ID不能为空");

        LambdaQueryWrapper<CourseResourcePartEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseResourcePartEntity::getContentId, query.getContentId());
        wrapper.eq(CourseResourcePartEntity::getResourceId, query.getResourceId());
        CourseResourcePartEntity partEntity = resourcePartManager.getOne(wrapper);

        // 赋值用户数据
        UserQuestionResultDTO userQuestion = new UserQuestionResultDTO();
        if (Objects.nonNull(partEntity)) {
            // 获取访问用户信息
            Long userId = LoginHelper.getUserId();
            ClassStudentResultDTO student = R.as(classStudentClient.findByStudentId(entity.getClassId(), userId));
            // 获取主学生信息
            ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(entity.getClassId(), userId));
            if (Objects.isNull(mainStudent)) {
                mainStudent = student;
            }
            // 赋值内容
            userQuestion.setStudentId(mainStudent.getStudentId());
            userQuestion.setRole(mainStudent.getClassRole());
            userQuestion.setMobile(student.getMobile());
            userQuestion.setNickname(mainStudent.getNickName());
            userQuestion.setAvatar(mainStudent.getAvatar());
            userQuestion.setXinqiNumber(student.getXinqiNumber());
            userQuestion.setStudentNumber(student.getStudentNumber());
            userQuestion.setIsReply(YesNoNumberEnum.NO.getCode());

            List<QuestionResultDTO> resultList = new ArrayList<>();
            // 转换答题数据
            if (Objects.nonNull(partEntity.getQuestions()) && CollectionUtils.isNotEmpty(partEntity.getQuestions())) {
                resultList = questionConvert.convertList(partEntity.getQuestions());
                userQuestion.setQuestions(resultList);
            }

            Boolean replyFlag = true;
            // 判断老师学生显示不同的数据
            if (Objects.equals(ClassRoleEnum.REPRESENTATIVE.getCode(), student.getClassRole())
                || Objects.equals(ClassRoleEnum.STUDENT.getCode(), student.getClassRole())) {
                // 获取答题数据
                LambdaQueryWrapper<CourseResourceInteractionLogEntity> wrapperLog = new LambdaQueryWrapper<>();
                wrapperLog.eq(CourseResourceInteractionLogEntity::getStudentId, mainStudent.getStudentId());
                wrapperLog.eq(CourseResourceInteractionLogEntity::getContentId, query.getContentId());
                wrapperLog.eq(CourseResourceInteractionLogEntity::getResourcePartId, query.getResourceId());
                CourseResourceInteractionLogEntity interactionLog = resourceInteractionLogManager.getOne(wrapperLog);

                if (Objects.nonNull(interactionLog) || entity.getEndTime().isBefore(LocalDateTime.now())) {
                    userQuestion.setIsReply(YesNoNumberEnum.YES.getCode());
                    replyFlag = true;
                } else {
                    replyFlag = false;
                }

                // 判断是否有答题数据（根据不同答题数据放回不同内容）
                resultList = QuestionUtil.tranAnswer(resultList, replyFlag, Objects.nonNull(interactionLog) ? interactionLog.getAnswer() : null);
                userQuestion.setQuestions(resultList);
            }
        }

        return userQuestion;
    }

    /**
     * 获取 互动环节 通过互动环节ID
     * @param query 资料ID
     */
    @Override
    public UserQuestionResultDTO selectPartByPartId(CourseResourceVideoQueryDTO query) {
        // 判断是否数据存在
        CourseResourceEntity entity = Optional.ofNullable(courseResourceBaseManager.getById(query.getContentId()))
            .orElseThrow(() -> CommonErrors.NOT_DATA.asException("course.resource.data.id.not.exit"));

        CommonErrors.BAD_REQUEST.check(Objects.nonNull(query.getPartId()), "互动环节ID不能为空");

        LambdaQueryWrapper<CourseResourcePartEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseResourcePartEntity::getId, query.getPartId());
        CourseResourcePartEntity partEntity = resourcePartManager.getOne(wrapper);

        // 校验是否有互动环节
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(partEntity), "未获取到互动环节");

        // 获取访问用户信息
        Long userId = LoginHelper.getUserId();
        ClassStudentResultDTO student = R.as(classStudentClient.findByStudentId(entity.getClassId(), userId));
        // 获取主学生信息
        ClassStudentResultDTO mainStudent = R.as(classStudentClient.findVirtualClassStudentByClassIdAndUserId(entity.getClassId(), userId));

        // 赋值用户数据
        UserQuestionResultDTO userQuestion = new UserQuestionResultDTO();
        //  没有主学生数据 则为 老师和助教
        if (Objects.nonNull(mainStudent)) {
            userQuestion.setStudentId(mainStudent.getStudentId());
            userQuestion.setRole(student.getClassRole());
            userQuestion.setMobile(student.getMobile());
            userQuestion.setNickname(mainStudent.getNickName());
            userQuestion.setAvatar(mainStudent.getAvatar());
            userQuestion.setXinqiNumber(student.getXinqiNumber());
            userQuestion.setStudentNumber(student.getStudentNumber());
            userQuestion.setIsReply(YesNoNumberEnum.NO.getCode());
        }

        List<QuestionResultDTO> resultList = new ArrayList<>();
        // 转换答题数据
        if (Objects.nonNull(partEntity.getQuestions()) && CollectionUtils.isNotEmpty(partEntity.getQuestions())) {
            resultList = questionConvert.convertList(partEntity.getQuestions());
            userQuestion.setQuestions(resultList);
        } else {
            // 旧数据转换
            List<CourseQuestionLibraryEntity> librarys = courseQuestionLibraryManager.findByPartId(query.getPartId());
            List<QuestionBaseDTO> questionBaseList = courseQuestionLibraryConvert.convertBase(librarys);
            // 转换选项
            questionBaseList = QuestionUtil.tranOptionList(questionBaseList);
            userQuestion.setQuestions(questionConvert.convertList(questionBaseList));
        }

        // 默认显示答题数据
        Boolean replyFlag = true;
        // 判断老师学生显示不同的数据
        if (Objects.equals(ClassRoleEnum.REPRESENTATIVE.getCode(), student.getClassRole())
            || Objects.equals(ClassRoleEnum.STUDENT.getCode(), student.getClassRole())) {
            // 获取答题数据
            LambdaQueryWrapper<CourseResourceInteractionLogEntity> wrapperLog = new LambdaQueryWrapper<>();
            wrapperLog.eq(CourseResourceInteractionLogEntity::getStudentId, mainStudent.getStudentId());
            wrapperLog.eq(CourseResourceInteractionLogEntity::getContentId, query.getContentId());
            wrapperLog.eq(CourseResourceInteractionLogEntity::getResourcePartId, query.getPartId());
            CourseResourceInteractionLogEntity interactionLog = resourceInteractionLogManager.getOne(wrapperLog);

            // 答题数据为空 查询旧表是否有答题数据
            if (Objects.isNull(interactionLog)) {
                List<CourseInteractionSubmitEntity> answerList = interactionSubmitManager.findStudentAnswer(query.getContentId(), query.getPartId(), userId);
                if (CollectionUtils.isNotEmpty(answerList)) {
                    interactionLog.setAnswer(resourceAnswerConvert.convertBaseAnswerList(answerList));
                    replyFlag = true;
                } else {
                    replyFlag = false;
                }
            }

            // 答题数据不为空 或 答题已结束 返回 已答题
            if (Objects.nonNull(interactionLog) || entity.getEndTime().isBefore(LocalDateTime.now())) {
                userQuestion.setIsReply(YesNoNumberEnum.YES.getCode());
                replyFlag = true;
            }
            // 判断是否有答题数据（根据不同答题数据返回不同内容）
            resultList = QuestionUtil.tranAnswer(resultList, replyFlag, Objects.nonNull(interactionLog) ? interactionLog.getAnswer() : null);
            userQuestion.setQuestions(resultList);
        }
        return userQuestion;
    }

    /**
     * 新增 资料
     * @param list 资料试题对象集合
     */
    @Override
    public void addBatchPart(List<CourseResourcePartEntity> list) {
        resourcePartManager.saveBatch(list);
    }

    /**
     * 删除 资料
     * @param contentId 资料ID
     */
    @Override
    public void deletePart(Long contentId) {
        LambdaQueryWrapper<CourseResourcePartEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseResourcePartEntity::getContentId, contentId);
        List<CourseResourcePartEntity> list = resourcePartManager.list(wrapper);
        resourcePartManager.removeBatchByIds(list, true);
    }

    /**
     * 批量 删除 资料 试题
     * @param contentIds 资料ID集合
     */
    @Override
    public void deleteBatchPart(List<Long> contentIds) {
        LambdaQueryWrapper<CourseResourcePartEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(CourseResourcePartEntity::getContentId, contentIds);
        List<CourseResourcePartEntity> list = resourcePartManager.list(wrapper);
        resourcePartManager.removeBatchByIds(list, true);
    }

}
